<?php namespace Phpcmf\Controllers;

class Cart extends \Phpcmf\Home\Module {

    public $config;

    public function __construct(...$params) {
        parent::__construct(...$params);
        $mid = dr_safe_filename(\Phpcmf\Service::L('input')->get('mid'));
        if (!$mid) {
            $this->_msg(0, dr_lang('模块参数mid不能为空'));
        }

        $this->_module_init($mid);

        $this->config = \Phpcmf\Service::M('app')->get_config(APP_DIR);
        if (!isset($this->config['module'][$mid]['open']) || !$this->config['module'][$mid]['open']) {
            $this->_msg(0, dr_lang('模块[%s]没有开启订单权限', $this->module['name']));
        }

        \Phpcmf\Service::V()->module($mid);
    }

    // 购物车列表
    public function index() {

        if (IS_POST) {

            $ids = \Phpcmf\Service::L('input')->get_post_ids();
            if (!$ids) {
                exit($this->_json(0, dr_lang('你还没有选择呢')));
            }

            $data = \Phpcmf\Service::M('cart', 'order')->my_items($this->module['dirname'], $ids);
            if (!$data) {
                exit($this->_json(0, dr_lang('无可用商品')));
            }

            foreach ($data as $t) {
                $rt = \Phpcmf\Service::M('cart', 'order')->get_module_row($t['mid'], $t['cid'], $t['sku_value']);
                if (isset($rt['code']) && !$rt['code']) {
                    exit($this->_msg(0, $rt['msg']));
                }
                \Phpcmf\Service::M('cart', 'order')->update_cart($t['id'], $rt['data']);
            }
            exit($this->_json(1, dr_lang('操作成功')));
        }

        $list = \Phpcmf\Service::M('cart', 'order')->my_list($this->module['dirname']);

        \Phpcmf\Service::V()->assign([
            'list' => $list,
            'module' => $this->get_cache('module-'.SITE_ID),
            'my_list' => $list,
            'meta_title' => dr_lang('我的购物车').SITE_SEOJOIN.SITE_NAME,
            'meta_keywords' => $this->get_cache('site', SITE_ID, 'config', 'SITE_KEYWORDS'),
            'meta_description' => $this->get_cache('site', SITE_ID, 'config', 'SITE_DESCRIPTION')
        ]);
        \Phpcmf\Service::V()->display('cart.html');
    }

    // 购物车数量
    public function nums() {
        $this->_json(1, 'ok', \Phpcmf\Service::M('cart', 'order')->my_count($this->module['dirname']));
    }

    // 删除购物车
    public function del() {

        $id = (int)\Phpcmf\Service::L('input')->get('id');
        !$id && exit($this->_json(0, dr_lang('id参数不存在')));

        exit($this->_json(1, dr_lang('操作成功'), \Phpcmf\Service::M('cart', 'order')->my_delete($this->module['dirname'], $id)));
    }

    // 更新购物车数量
    public function update() {

        $id = (int)\Phpcmf\Service::L('input')->get('id');
        $num = max(1, (int)\Phpcmf\Service::L('input')->get('num'));
        !$id && exit($this->_json(0, dr_lang('id参数不存在')));

        $data = \Phpcmf\Service::M('cart', 'order')->my_info($this->module['dirname'], $id);
        !$data && exit($this->_jsonp(0, dr_lang('商品[%s]不存在', $id)));

        \Phpcmf\Service::M('cart', 'order')->update_num($id, $num);

        exit($this->_json(1, dr_lang('操作成功'), [
            'nums' => \Phpcmf\Service::M('cart', 'order')->my_count($this->module['dirname']),
            'total' => number_format($data['price'] * $num, 2)
        ]));
    }

    // 加入购物车
    public function add() {

        $id = (int)\Phpcmf\Service::L('input')->get('id');
        if (!$id) {
            $this->_json(0, dr_lang('商品id参数不存在'));
        }

        // 获取付款价格
        $num = max(1, (int)\Phpcmf\Service::L('input')->get('num'));
        $sku = dr_safe_replace(\Phpcmf\Service::L('input')->get('sku'), 'undefined');
        
        $rt = \Phpcmf\Service::M('cart', 'order')->add_cart($this->module['dirname'], $id, $sku, $num);
        if (!$rt['code']) {
            $this->_json(0, $rt['msg']);
        }

        $this->_json(1, dr_lang('已加入购物车'), \Phpcmf\Service::M('cart', 'order')->my_count($this->module['dirname']));
    }

    // 加入购物车并选择属性
    public function select() {


        $id = (int)\Phpcmf\Service::L('input')->get('id');
        if (!$id) {
            $this->_json(0, dr_lang('商品id参数不存在'));
        }

        // 查询商品
        $data = \Phpcmf\Service::M()->table(SITE_ID.'_'.$this->module['dirname'])->get($id);
        if (!$data) {
            return dr_return_data(0, dr_lang('此商品[%s]不存在', $id));
        } elseif (isset($data['zt']) && !$data['zt']) {
            return dr_return_data(0, dr_lang('此商品[%s]已经下架', $id));
        }

        // 判断是否存在多属性商品
        $price_sku = dr_string2array($data['price_sku']);
        if ($price_sku) {
            // 存在组合商品
            ob_start();
            \Phpcmf\Service::V()->assign([
                'item' => $data,
                'price' => $data['price'],
                'price_sku' => $price_sku,
            ]);
            \Phpcmf\Service::V()->display('cart_select.html');
            $html = ob_get_clean();
            exit($this->_json(2, $html, '/index.php?is_ajax=1&s=order&c=cart&m=add&id='.$id.'&mid='.$this->module['dirname']));
        }

        // 获取付款价格
        $num = max(1, (int)\Phpcmf\Service::L('input')->get('num'));
        $rt = \Phpcmf\Service::M('cart', 'order')->add_cart($this->module['dirname'], $id, '', $num);
        if (!$rt['code']) {
            $this->_json(0, $rt['msg']);
        }

        $this->_json(1, dr_lang('已加入购物车'), \Phpcmf\Service::M('cart', 'order')->my_count($this->module['dirname']));
    }

    // 购物车点购买
    public function order() {

        $ids = \Phpcmf\Service::L('input')->get_post_ids();
        if (!$ids) {
            $this->_json(0, dr_lang('购物车无商品'));
        }

        $cart = \Phpcmf\Service::M()->db->table(SITE_ID.'_order_cart')->where('mid', $this->module['dirname'])->whereIn('id', $ids)->get()->getResultArray();
        if (!$cart) {
            $this->_json(0, dr_lang('购物车中商品无效'));
        }

        $cid = [];
        foreach ($cart as $t) {
            $rt = \Phpcmf\Service::M('cart', 'order')->get_module_row($this->module['dirname'], $t['cid'], $t['sku_value']);
            if (!$rt['code']) {
                $this->_json(0, $rt['msg']);
            } elseif ($this->config['module'][$this->module['dirname']]['quantity'] && !$rt['data']['quantity']) {
                $this->_json(0, dr_lang('该商品【%s】已销售完', $rt['data']['title']));
            } elseif ($this->config['module'][$this->module['dirname']]['quantity'] && $rt['data']['quantity'] < $t['quantity']) {
                $this->_json(0, dr_lang('该商品【%s】库存不足，商品剩余：%s', $rt['data']['title'], $rt['data']['quantity']));
            }
            $cid[] = $t['id'];
        }

        $cid = implode(',', $cid);

        exit($this->_json(
            1, dr_lang('正在为您下订单'), [
                'url' => dr_url('order/order/checkout', ['mid' => $this->module['dirname'], 'id' => $cid])
            ]
        ));
    }

}
